#!/bin/bash

# 商家后端系统 Docker 启动脚本

set -e

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 日志函数
log_info() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

log_warn() {
    echo -e "${YELLOW}[WARN]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

log_header() {
    echo -e "${BLUE}========================================${NC}"
    echo -e "${BLUE}$1${NC}"
    echo -e "${BLUE}========================================${NC}"
}

# 检查Docker环境
check_docker() {
    log_info "检查Docker环境..."
    
    if ! command -v docker &> /dev/null; then
        log_error "Docker未安装，请先安装Docker"
        exit 1
    fi
    
    if ! docker info &> /dev/null; then
        log_error "Docker未启动，请先启动Docker服务"
        exit 1
    fi
    
    if ! command -v docker-compose &> /dev/null; then
        log_error "Docker Compose未安装"
        exit 1
    fi
    
    log_info "Docker环境检查通过"
}

# 清理现有容器
cleanup() {
    log_info "停止并清理现有容器..."
    docker-compose down --remove-orphans
}

# 构建并启动服务
start_services() {
    log_info "构建并启动服务..."
    docker-compose up -d --build
}

# 等待服务启动
wait_for_services() {
    log_info "等待服务启动..."
    
    # 等待MySQL启动
    log_info "等待MySQL启动..."
    for i in {1..60}; do
        if docker-compose exec -T mysql mysqladmin ping -h localhost -u root -p123456 --silent; then
            log_info "MySQL启动成功"
            break
        fi
        if [ $i -eq 60 ]; then
            log_error "MySQL启动超时"
            exit 1
        fi
        sleep 2
    done
    
    # 等待后端应用启动
    log_info "等待后端应用启动..."
    for i in {1..60}; do
        if curl -f -s http://localhost:8080/test/health > /dev/null; then
            log_info "后端应用启动成功"
            break
        fi
        if [ $i -eq 60 ]; then
            log_warn "后端应用启动超时，请检查日志"
            break
        fi
        sleep 3
    done
}

# 显示服务状态
show_status() {
    log_info "检查服务状态..."
    docker-compose ps
}

# 显示访问信息
show_access_info() {
    log_header "服务启动完成！"
    echo
    echo "访问地址:"
    echo "- 后端API: http://localhost:8080"
    echo "- 健康检查: http://localhost:8080/test/health"
    echo "- MySQL: localhost:3306"
    echo
    echo "默认账号:"
    echo "- 管理员: admin/123456"
    echo "- 演示商家: demo/123456"
    echo
    echo "常用命令:"
    echo "- 查看所有日志: docker-compose logs -f"
    echo "- 查看后端日志: docker-compose logs -f merchant-backend"
    echo "- 查看数据库日志: docker-compose logs -f mysql"
    echo "- 停止服务: docker-compose down"
    echo "- 重启服务: docker-compose restart"
    echo
    log_header "启动完成"
}

# 主函数
main() {
    log_header "商家后端系统 Docker 启动脚本"
    
    check_docker
    cleanup
    start_services
    wait_for_services
    show_status
    show_access_info
}

# 执行主函数
main
